package com.MonkWorks.timedormitory;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.MonkWorks.clockDTO.Job;
import com.MonkWorks.clockDTO.User;
import com.MonkWorks.timedormitoryDB.ItimeProvider;
import com.MonkWorks.timedormitoryDB.TimeDB;


public class PunchActivity extends Activity {
	//bringing in the ItimeProvider class
	ItimeProvider timeDB;
	
	//set up the current time
	DateFormat format = new SimpleDateFormat("HH:mm:ss");   
	
	//create some constants for location
	public static double LATITUDE;
	public static double LONGITUDE;
	private Button button_ClockIn;
	private Button button_ClockOut;
	private Button button_AddJob;
	private TextView clockIn;
	private TextView clockOut;
	private Button button_LogOut;
	private String clientName;
	private Spinner jobSel;
	private String JobValue;
	
	//address from clientActivity is sent to this variable
	private String address;
	//where the username from clock in is sent
	private String username;
	//description from clientActivity is sent to this variable
	 private String description;
	 
	 Job currentJob;
	 
	 
	private void initComponent(){
		//implement timeProviderStub
		timeDB = new TimeDB(this);
		
		button_ClockIn = (Button)findViewById(R.id.btnClockIn);
		clockIn = (TextView)findViewById(R.id.tvClockIn);
		clockOut = (TextView)findViewById(R.id.tvClockout);
		button_ClockOut = (Button)findViewById(R.id.btnOut);
		button_AddJob = (Button)findViewById(R.id.btnAddJob);
		button_LogOut = (Button)findViewById(R.id.btnLogOut);
		jobSel = (Spinner)findViewById(R.id.spinner1);
	    
	
		//retrieves extras from other activityes
		getExtras();
		
		
		
		//bring in user object
		final User currentUser = new User();
		currentUser.setUsername(clientName);
		
		
		//spinner stuff
				List<String> fetchJob;
				try{
				fetchJob = timeDB.fetchJobByUser(clientName);
				Log.i("PunchActivity", "fetchJob for Spinner");
				ArrayAdapter jobAdapter = new ArrayAdapter<String>(this,
						android.R.layout.simple_dropdown_item_1line, fetchJob);
				
				//finalize the values that go into the spinner
				jobSel.setAdapter(jobAdapter);

				
				}
				catch (Exception e)
				{
					popup("unable to populate spinner");
					Log.e("PunchActivity", "FetchJob");
				}
		 jobSel.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				JobValue = jobSel.getSelectedItem().toString();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
			 
		});
				
		
		 button_ClockIn.setOnClickListener(new View.OnClickListener() {
			 
			public void onClick(View v) {
				//initiate the clockin variable
				String Clockintime = format.format(System.currentTimeMillis());
				
				JobInfo();
				//check to see if job is already clocked in on
				if(timeDB.clockCheck(currentJob) == false)
				{
					popup("Already Clocked In");
				}
				else{
				//implement clock in method. this method needs current user, location, jobID, and time 
				try {
					JobInfo();
					timeDB.clockIn(currentUser,  Clockintime, currentJob, LATITUDE, LONGITUDE);
					
				} catch (Exception e) {
					popup("Unable to clockon");
					Log.e("PunchActivity", "ClockIn failed");
				}
			     clockIn.setText(Clockintime);
				popup("Clock In Time: " + Clockintime);
				}
			}
		});
		 
		button_ClockOut.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				//initiate the clockout variable
				String ClockOuttime = format.format(System.currentTimeMillis());
				
				
				JobInfo();
				//check to see if job is aready clocked out of
				if(timeDB.clockOutCheck(currentJob) == false)
				{
					popup("Already Clocked Out");
				}
				else{
					//implement clock out method. this method needs current user, location, jobID, and time
				try {
					JobInfo();
					timeDB.clockOut(currentUser, ClockOuttime, currentJob, LATITUDE, LONGITUDE);
				} catch (Exception e) {
					popup("Unable to clockout");
					Log.e("PunchActivity", "ClockOut failed");
				}
				popup("Clock Out Time: " + ClockOuttime);
				clockOut.setText(ClockOuttime);
				}
			}
		});
		
		 button_AddJob.setOnClickListener(new View.OnClickListener() {
				
				public void onClick(View v) {
				
					
					Intent  MIntent = new Intent(v.getContext(), ClientActivity.class);
					MIntent.putExtra("clientName", clientName);
					startActivityForResult(MIntent, 0);
					 
				}
			});
		
		 
			button_LogOut = (Button) findViewById(R.id.btnLogOut);
			button_LogOut.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					Intent CIntent = new Intent(v.getContext(),
							LoginActivity.class);
					startActivityForResult(CIntent, 0);
					popup("You have logged out");

				}
			});
		 
	}
	
	
	
	private void getExtras(){
		Bundle extras = getIntent().getExtras();
		if(extras !=null) {
		clientName = extras.getString("username");
		}
	}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_punch);
        initComponent();
        //start tracking location
        CurrentLocation();
        
    	
    }
    

    protected void popup(String message) {
    	// this is how we make a popup.
    	Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    public void JobInfo()
    {
    	//call the method to find job by name and return a list
    	List<Job>allJobs;
    	allJobs = timeDB.findJobByName(JobValue);
    	//iterate the object results
    	Iterator<Job>JobOb = allJobs.iterator();
    	//iterate over the list in the object value
    	Job i = JobOb.next();
    	//assign appropriate values
    	currentJob = i;
    	 
    		
    }
    
    
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_punch, menu);
		return true;
	} 
    	 
    public boolean onOptionsItemSelected(MenuItem item) {
    
      //Logs the user out
      if (item.getItemId() == R.id.Logoff) {
    	  
    	  Intent  MIntent = new Intent(getBaseContext(),LoginActivity.class);
			startActivityForResult(MIntent, 0);
			popup("You have logged out");
        return true;
      }


      return (super.onOptionsItemSelected(item));
    }

    
    public void CurrentLocation()
    {
    	LocationManager loc = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    	LocationListener loclist = new myLocationListener();
    	loc.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, loclist);
    }
    	class myLocationListener implements LocationListener{

			@Override
			public void onLocationChanged(Location location) {
				if(location != null)
				{
					LATITUDE = location.getLatitude();
					LONGITUDE = location.getLongitude();
					
					
				}
				
			}

			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onStatusChanged(String provider, int status,
					Bundle extras) {
				// TODO Auto-generated method stub
				
			}
    		
    	}
    }
 
   
    


